package cm.wc.util;

import cm.wc.domain.Book;
import cm.wc.util.DateTimeUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.FileReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.*;
import java.time.LocalDate;
import java.util.Properties;

/**
 * @ClassName:JDBCUtil
 * @Author: 鹿建文
 * @Date: 2022/3/29  - 16:27
 * @Describe:
 */
@Slf4j
public class JDBCUtil {
    private static String url;
    private static String user;
    private static String password;

    static {
        Properties properties = new Properties();
        String propertiesFile = "src/main/resources/mysql.properties";

        try {
            //加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            properties.load(new FileReader(propertiesFile));
            log.info("加载数据裤连接属性文件{}",propertiesFile);
        } catch (IOException e) {
            log.error("属性文件不存在{}",propertiesFile);
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            log.error("驱动加载失败{}",propertiesFile) ;
        }
        url = properties.getProperty("url");
        user = properties.getProperty("user");
        password = properties.getProperty("password");
    }





    public static Connection getConnection()  {
        Connection conn = null;
        try {
            log.info("{}创建connection对象{}成功",user,conn);
            conn = DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            log.error("{}获取连接{}shibai",user,url);
            e.printStackTrace();
        }
        return conn;
    }


    public static void release(Connection conn, Statement stmt, ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
                log.info("释放resultset对象{}成功",rs);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            log.error("释放resultset对象{}失败",rs);
        } finally {
            try {
                if (stmt != null) {
                    stmt.close();
                    log.info("释放statement对象{}成功",stmt);
                }
            } catch (SQLException e) {
                e.printStackTrace();
                log.error("释放statement对象{}失败",stmt);
            } finally {
                try {
                    if (conn != null) {
                        conn.close();
                        log.info("释放connection对象{}成功",conn);
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                    log.error("释放connection对象{}失败",conn);
                } finally {
                }
            }
        }
    }
}